package controllers

import (
	"encoding/json"
	"github.com/beego/beego/v2/core/validation"
	beego "github.com/beego/beego/v2/server/web"
	"movie/models"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type MovieController struct {
	beego.Controller
}

func (c *MovieController) Login() {
	user := c.GetString("user")
	password := c.GetString("password")

	key := "users-" + user
	count, _ := models.Rds.Get(key).Int()
	if count >= 3 {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "密码连续错误三次,锁定两小时",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var users models.User
	err := models.DB.Model(&models.User{}).Where("user=?", user).First(&users).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "账号不存在,请重新输入",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if users.Password == password {
		models.Rds.Del(key)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "登录成功",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		models.Rds.Incr(key)
		models.Rds.Expire(key, time.Hour*2)
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "密码错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}

func (c *MovieController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price", 64)
	types := c.GetString("types")
	img := c.GetString("img")
	introduce := c.GetString("introduce")
	user := c.GetString("user")

	valid := validation.Validation{}
	valid.Required("name", name).Message("电影名称不能为空")
	valid.Required("types", types).Message("电影类型不能为空")
	valid.Required("img", img).Message("电影图片不能为空")
	valid.Required("introduce", introduce).Message("电影简介不能为空")
	valid.Required("user", user).Message("电影主演不能为空")

	if valid.HasErrors() {
		for _, e := range valid.Errors {
			c.Data["json"] = models.JsonR{
				Code: 500,
				Msg:  e.Message,
				Data: nil,
			}
			c.ServeJSON()
		}
	}

	var film = models.Film{
		Name:      name,
		Price:     price,
		Types:     types,
		Img:       img,
		Introduce: introduce,
		User:      user,
	}
	err := models.DB.Model(&models.Film{}).Create(&film).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
}

func (c *MovieController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "获取文件失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()

	if header.Size > 5*1024*1024 {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "文件大小不能超过5Mb",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	ext := strings.ToLower(filepath.Ext(header.Filename))
	exts := map[string]bool{
		".jpg": true,
		".png": true,
	}
	if !exts[ext] {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "文件类型必须为jpg、png",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "文件上传成功",
		Data: "http://127.0.0.1:8080/" + path,
	}
	c.ServeJSON()

}

func (c *MovieController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 10)
	name := c.GetString("name")
	var count int64
	query := models.DB.Model(&models.Film{})
	offset := (page - 1) * size
	query.Count(&count)

	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	var films []models.Film
	pageDate := make(map[string]interface{})
	key := "film-" + strconv.Itoa(page)
	val, err := models.Rds.Get(key).Result()
	if err != nil {
		err = query.Offset(offset).Limit(size).Find(&films).Error
		if err != nil {
			c.Data["json"] = models.JsonR{
				Code: 500,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		pageDate["count"] = count
		pageDate["films"] = films
		xx, _ := json.Marshal(&pageDate)
		value := string(xx)
		models.Rds.Set(key, value, time.Second*5)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "展示成功-mysql",
			Data: pageDate,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &pageDate)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: pageDate,
		}
		c.ServeJSON()
	}

}

func (c *MovieController) Info() {
	id, _ := c.GetInt("id")
	keys := "rank"
	models.Rds.ZIncrBy(keys, 1, strconv.Itoa(id))
	var film models.Film
	key := "film" + strconv.Itoa(id)
	val, err := models.Rds.Get(key).Result()
	if err != nil {
		err = models.DB.Model(&models.Film{}).Where("id=?", id).First(&film).Error
		if err != nil {
			c.Data["json"] = models.JsonR{
				Code: 500,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		xx, _ := json.Marshal(&film)
		value := string(xx)
		models.Rds.Set(key, value, 0)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "详情展示成功-mysql",
			Data: film,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &film)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "详情展示成功-redis",
			Data: film,
		}
		c.ServeJSON()
	}

}

func (c *MovieController) Rank() {
	key := "rank"
	Rank, err := models.Rds.ZRevRange(key, 0, 9).Result()
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "排行榜获取失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var films []models.Film
	for _, s := range Rank {
		var film models.Film
		err = models.DB.Model(&models.Film{}).Where("id=?", s).First(&film).Error
		if err != nil {
			break
		}
		films = append(films, film)
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "排行榜展示成功",
		Data: films,
	}
	c.ServeJSON()
}
